package org.dromara.demo.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

public class CustomSampleUtil {

    public static KeyStorePasswordPair getKeyStorePasswordPair(String certificateFile, String privateKeyFile) throws Exception {
        KeyStorePasswordPair pair = new KeyStorePasswordPair();
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);

        // Load certificate
        FileInputStream certInputStream = new FileInputStream(certificateFile);
        java.security.cert.Certificate cert = java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(certInputStream);
        certInputStream.close();
        keyStore.setCertificateEntry("certificate", cert);

        // Load private key
        FileInputStream keyInputStream = new FileInputStream(privateKeyFile);
        java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA");
        java.security.spec.PKCS8EncodedKeySpec keySpec = new java.security.spec.PKCS8EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(readFileToBytes(privateKeyFile)));
        java.security.PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        keyInputStream.close();

        keyStore.setKeyEntry("private", privateKey, "password".toCharArray(), new java.security.cert.Certificate[]{cert});

        pair.keyStore = keyStore;
        pair.keyPassword = "password".toCharArray();

        return pair;
    }

    private static byte[] readFileToBytes(String filePath) throws IOException {
        java.nio.file.Path path = java.nio.file.Paths.get(filePath);
        return java.nio.file.Files.readAllBytes(path);
    }

    public static class KeyStorePasswordPair {
        public KeyStore keyStore;
        public char[] keyPassword;
    }
}
